import React            from 'react';
import {connect}        from "react-redux";

import {PHONE}          from '../../utils/Format';
import {ident}          from "../../actions/active";
import './ident.scss';

const TIMEOUT = 15;

class Ident extends React.Component {

    state = {active: false};
    timeout = TIMEOUT;
    mounted = false;

    _start(){
        this.setState({active: true});
        this._countDown();
    }

    _reset(){
        this.timeout = TIMEOUT;
        this.setState({active: false});
    }

    _countDown(){
        setTimeout(() => {
            if(this.mounted){
                if(0 < this.timeout--){
                    this.forceUpdate();
                    return this._countDown();
                }
                this._reset();
            }
        }, 1000);
    }

    _ident(ident, p){
        _.invoke(this.props, 'getIdent', ident, p);
    }

    componentDidMount(){
        this.mounted = true;
    }

    componentWillUnmount(){
        this.mounted = false;
    }

    ident(){
        var phone = _.get(this.props, 'phone');
        if(PHONE.test(phone)){
            return _.invoke(this.props, 'preIdent', phone).then(r => {
                if(r){
                    this._start();
                    this.props.ident(phone).then(r => this._ident(r, phone));
                }
            });
        }
        return this._ident(false);
    }

    render(){
        var {active} = this.state;
        return (
            <div className={`ident${active ? ' active' : ''}`} onClick={() => this.ident()}>
                <div className="i-btn flex-avg i-ident">获取验证码</div>
                <div className="i-btn flex-avg i-count">{this.timeout}s后重新发送</div>
            </div>
        );
    }

}

export default connect(undefined, {ident})(Ident);
